package fr.gestschool.addUser.controler;

import java.util.Collection;
import java.util.Iterator;

import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;


import fr.gestschool.addUser.bean.AddUserBean;
import fr.gestschool.addUser.view.AddUserView;
import fr.gestschool.login.User.User;
import fr.gestschool.login.User.UserDAO;
import fr.gestschool.login.bean.LoginBean;
import fr.gestschool.login.view.LoginView;
import fr.gestschool.util.Utils;


public class AddUserControler {
		AddUserBean bean;
		AddUserView view;
		
		public AddUserControler() {
			
			this.bean = new AddUserBean();
			this.view = new AddUserView();
		}
		
		
		
		public AddUserBean getBean() {
			return bean;
		}
		public void setBean(AddUserBean bean) {
			this.bean = bean;
		}
		public AddUserView getView() {
			return view;
		}
		public void setView(AddUserView view) {
			this.view = view;
		}
		
		
		public String validate(){
			HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();

			InitialContext ctx;
			try {
	
				ctx = Utils.getInitialContext();
				UserDAO dao = (UserDAO) ctx.lookup("UserDAOBean/remote");
				Collection<User> colUser = dao.findUserByLogin((String)view.getLogin().getValue(),(String)view.getMdp().getValue());

				if(colUser.size()!=0){
					Iterator<User> it = colUser.iterator();
					
					System.out.println("login "+it.next().getLogin()+" mdp "+it.next().getPassword());
					System.out.println(",otnull");
					return "loginError";					
				}else{
				System.out.println("null");
				User user = new User();
				user.setLogin((String)view.getLogin().getValue());
				user.setPassword((String)view.getMdp().getValue());
				user.setSkin((String)view.getSkin().getValue());
				dao.addUser(user);
				request.setAttribute("skin","2");
				return "loginOK";
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return "loginError";

		
	}

}


